package fons.navigator.views.piemap;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.nodes.PPath;


public class Anchor extends PPath {    
	private static final long serialVersionUID = 1L;
	
	private final double length;
	
    static Anchor fromTo (PNode source, PNode dest, Anchorable anchor) {
        
        Point2D anchorPoint = dest.localToGlobal(anchor.getAnchorOn(dest));
        Point2D originPoint = source.getBoundsReference().getOrigin();
        originPoint.setLocation(
        		originPoint.getX() - source.getFullBoundsReference().getHeight()/2, 
        		originPoint.getY() + source.getFullBoundsReference().getHeight()/2);
        
        Line2D line = new Line2D.Double(source.localToParent(originPoint),
				  source.globalToLocal(source.localToParent(anchorPoint)));
        
        Anchor a = new Anchor(line.getX1(), line.getX2(), line.getY1(), line.getY2());
        a.setPathTo(line);
        
        return a;
    }
    
    
    static Anchor fromParentTo (PNode parent, Point2D localDest) {
    	Point2D start = new Point2D.Double(0, 0);
        Point2D end = localDest;
        
        Line2D line = new Line2D.Double(start, end);
        Anchor a = new Anchor(line.getX1(), line.getX2(), line.getY1(), line.getY2());
        parent.addChild(a);
        a.moveToBack();
        a.setPathTo(line);
        
        return a;        
    }
    
    public static Anchor fromTo (PNode parent, Point2D localOrigin, Point2D globalDest) {
    	Line2D line = new Line2D.Double(localOrigin, parent.globalToLocal((Point2D)globalDest.clone()));
    	Anchor a = new Anchor(line.getX1(), line.getX2(), line.getY1(), line.getY2());
    	a.setPathTo(line);
    	return a;    	
    }
    
    private Anchor (double x1, double x2, double y1, double y2) {
    	this.length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
    }
    
    public double getLength () {
    	return this.length;
    }
}
